package com.mxchip.livestarmobile.mobile.ui.meeting

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.mxchip.livestarmobile.R
import com.mxchip.livestarmobile.mobile.db.entity.Contact
import com.mxchip.livestarmobile.mobile.ui.ItemHolder
import kotlinx.android.synthetic.main.item_meeting_invite.*

class MeetingInviteRecyclerAdapter(private val onClickListener: ((View, Contact) -> Unit)? = null) : RecyclerView.Adapter<ItemHolder>()  {

    var data: List<Contact> = emptyList()

    private val _selected: MutableList<Contact> = arrayListOf()

    val selected: List<Contact>
        get() = _selected

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemHolder {
        val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.item_meeting_invite, parent, false)
        return ItemHolder(view)
    }

    override fun getItemCount(): Int {
        return data.size
    }

    override fun onBindViewHolder(holder: ItemHolder, position: Int) {

        val bean = data[position]


        holder.name.text = bean.fullName
        holder.number.text = bean.hxbNumber?.trimStart('0')

        holder.check_box.setOnCheckedChangeListener { buttonView, isChecked ->

            if(!buttonView.isClickable) {
                return@setOnCheckedChangeListener
            }

            if(isChecked) {
                _selected.add(bean)
            } else {
                _selected.removeAll {
                    it.hxbNumber == bean.hxbNumber
                }
            }

            Log.e("MeetingInviteRecyclerAdapter", "selected $_selected")
        }

        holder.containerView.setOnClickListener {

            holder.check_box.isChecked = !holder.check_box.isChecked

            onClickListener?.invoke(it, bean)
        }
    }
}